<?php
class DictCn {
    private $mWords = array();
    private $mDoc   = null;
    public function __construct() {
        $this->mDoc = new DOMDocument();
    }
    public function lookup($word) {
        $xml=$this->getXML($word);
        if (!$xml) {
            return false;
        }
        $this->mDoc->loadXML($xml);
        $def=$this->getFirstNodeValue('def');
        if ($def=='Not Found' || !$def) {
            return false;
        }
        $word=array(
            'define'=>$def,
            'examples'=>array(),
            'pronounce'=>null
        );
        $word['define']=$def;
        $sents=$this->mDoc->getElementsByTagName('sent');
        for ($i=0;$i<$sents->length;$i++) {
            $word['examples'][] = $sents->item($i)->nodeValue;
        }
        $word['pronounce']=$this->getFirstNodeValue('pron');
        return $word;
    }
    private function getXML($word) {
        $url='http://dict.cn/ws.php?utf8=true&q='.urlencode($word);
        for ($try=0;$try<2;$try++) {
            if ($xml=@file_get_contents($url)) {
                return $xml;
            }
        }
        return false;
    }
    private function getFirstNodeValue($tag) {
        $items=$this->mDoc->getElementsByTagName($tag);
        if ($items->length>0) {
            return $items->item(0)->nodeValue;
        }
        return '';
    }
}
